<template>
	<view class="container">
		<view class="search-box">
			<uni-icons type="search" size="20" color="#999" @click="handleInput"></uni-icons>
			<input v-model="inputVal" placeholder="请输入关键字符" @input="handleInput" class="search-input"
				placeholder-class="placeholder-style" />
			<uni-icons v-if="inputVal" type="clear" size="20" color="#999" @click="clearInput"></uni-icons>
		</view>

		<view class="table-container">
			<view class="table-header">
				<view class="table-cell header-cell">品名</view>
				<view class="table-cell header-cell">数量</view>
				<view class="table-cell header-cell">扫码状态</view>
				<view class="table-cell header-cell time-header" @click="toggleSort">
					完成时间
				</view>
				<view class="table-cell header-cell time-header" @click="toggleSort">
					创建时间
				</view>
			</view>

			<!-- <view class="table-body"> -->
			<!-- 修改滚动容器结构 -->
			<scroll-view 
			  scroll-y 
			  class="table-body" 
			  :style="{height: scrollHeight + 'px'}"
			  @scrolltolower="handleScrollToLower"
			>
				<view class="table-row" v-for="(item, index) in input" :key="index" @click="spreadRow(index)">
					<view class="table-cell time-cell">{{item.goodsname}}</view>
					<view class="table-cell time-cell">{{item.goodsqty}}</view>
					<view class="table-cell code-cell">{{item.drug_status === '1' ? '完成' : '未完成'}}</view>
					<view class="table-cell time-cell">{{item.drug_time}}</view>
					<view class="table-cell time-cell">{{item.credate}}</view>
				</view>

				<view v-if="input.length === 0" class="empty-tip">
					<image src="/static/empty.png" mode="aspectFit"></image>
					<text>暂无数据</text>
				</view>
			<!-- </view> -->
			</scroll-view>
		</view>
		<!-- <view> -->
		<!-- <uni-popup ref="alertDialog" type="dialog">
				<uni-popup-dialog type="info" cancelText="关闭" confirmText="同意" title="通知" content="是否退出当前账号"
					@confirm="dialogConfirm">
				</uni-popup-dialog>
			</uni-popup> -->
		<!-- </view> -->
	</view>
</template>

<script>
	import {
		scanCode,
		getCode,
		getDuryList,
		endDury
	} from '../../config/api/api.js';
	import {
		getToken,
		login,
		logout
	} from '../../config/comm'
	import uniIcon from '../../uni_modules/uni-icons/components/uni-icons/uni-icons.vue'
	import uniDatetimePicker from '../../uni_modules/uni-datetime-picker/components/uni-datetime-picker/uni-datetime-picker.vue'
	import moment from 'moment'

	function formatDate(date) {
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0');
		const day = String(date.getDate()).padStart(2, '0');
		const hours = String(date.getHours()).padStart(2, '0');
		const minutes = String(date.getMinutes()).padStart(2, '0');
		const seconds = String(date.getSeconds()).padStart(2, '0');

		return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
	}

	export default {
		data() {
			return {
				input: [],
				audio: uni.createInnerAudioContext(),
				except_arr: [],
				sortOrder: 'desc',
				timeRange: [moment().subtract(1, 'days').startOf('day').format('YYYY-MM-DD HH:mm:ss'), moment().format(
					'YYYY-MM-DD HH:mm:ss')],
				total: 1,
				page: 1,
				current: 1,
				inputVal: '',
				timer: null, // 防抖计时器
				scrollHeight: 0, // 动态计算高度
				loading: false, // 加载锁
				noMore: false // 无数据标志
			}
		},
		components: {
			uniIcon,
			uniDatetimePicker
		},
		onLoad() {
			// #ifdef APP-PLUS
			  if (plus.os.name.toLowerCase() === 'android') {
			    const webview = this.$mp.page.$getAppWebview();
			    webview.setStyle({
			      scrollIndicator: 'none', // 隐藏滚动条提升性能
			      bounce: 'vertical'      // 允许弹性滚动
			    });
			  }
			  // #endif
			this.audio.src = '/static/25.mp3';
			this.audio.volume = 1;
			this.fetch(); // 初始化加载数据
		},
		onUnload() {
			// #ifdef APP-PLUS
			uni.$off('xwscan')
			// #endif
		},
		onPullDownRefresh() {
			this.current = 1;
			this.input = [];
			this.fetch()
		},
		// onBackPress() {
		// 	this.$refs.alertDialog.open()
		// 	return true;
		// },
		// onReachBottom() {
		//   if (this.current < this.page && !this.noMore) {
		//     this.current++;
		//     this.fetch();
		//   }
		// },
		mounted() {
			this.calcScrollHeight();
			// 监听窗口变化重新计算
			uni.onWindowResize(() => this.calcScrollHeight());
		},
		methods: {
			handleScrollToLower() {
			  if (this.current < this.page && !this.loading) {
			    this.current++;
			    this.fetch();
			    
			    // 安卓兼容：强制重绘滚动容器
			    // #ifdef APP-PLUS && ANDROID
			    this.scrollHeight += 1; // 微调高度触发重新计算
			    this.$nextTick(() => {
			      this.scrollHeight -= 1;
			    });
			    // #endif
			  }
			},
			calcScrollHeight() {
				const systemInfo = uni.getSystemInfoSync();
				this.scrollHeight = systemInfo.windowHeight - 120; // 减去顶部搜索框等固定高度
			},
			// 输入处理（带防抖）
			handleInput(value) {
				this.inputVal = value.target.value;
				this.noMore = false;
				this.reset();
			},
			// 清空输入
			clearInput() {
				this.inputVal = '';
				this.noMore = false;
				this.reset();
			},
			// 重置并重新加载数据
			reset() {
				this.current = 1;
				this.input = [];
				this.fetch();
			},
			toggleSort() {
				this.sortOrder = this.sortOrder === 'asc' ? 'desc' : 'asc';
				this.reset();
			},
			async fetch() {
				
				if (this.loading || this.noMore) return;
				uni.showLoading({
					title: '加载中...'
				});
				try {
					const {
						data: {
							data,
							total
						}
					} = await getDuryList({
						page: this.current,
						keys: this.inputVal
					});
					if (data.length === 0) {
					      this.noMore = true;
					      return;
					}
					if (data) {
						this.input.push(...data.map(el => ({
							// goodsname: `${el.lsdtlid}-${el.goodsname}`,
							goodsname: `${el.goodsid}-${el.goodssfid}-${el.lotno}-${el.goodsname}`,
							goodsqty: el.goodsqty,
							drug_status: el.drug_status,
							drug_time: el.drug_time,
							credate: el.credate,
							lsid: el.lsdtlid
						})));
						this.total = total
						this.page = Math.ceil(total / 20)
						
						// 安卓专属：强制重置滚动检测
						      // #ifdef APP-PLUS && ANDROID
						      await this.$nextTick();
						      const query = uni.createSelectorQuery().in(this);
						      query.select('.table-body').boundingClientRect(data => {
						        if (data.height < this.scrollHeight + 100) {
						          this.current++; // 自动触发下一页
						          this.fetch();
						        }
						      }).exec();
						      // #endif
					}
				} catch (e) {
					console.error(e);
				} finally {
					uni.hideLoading();
					uni.stopPullDownRefresh();
				}
			},
			spreadRow(index) {
				console.log('spreadRow', index, this.input[index])
				this.input[index]
				uni.navigateTo({
					url: `/pages/lostDtl/lostDtl?dtlId=${this.input[index].lsid}&status=${this.input[index].drug_status}&sum=${this.input[index].goodsqty}`,
				})
			},
			async scanCode() {
				uni.scanCode({
					onlyFromCamera: true,
					success: (res) => {
						if (this.except_arr.includes(res.result)) {
							uni.showToast({
								title: '扫码重复',
								icon: 'none'
							})
						} else {
							this.handleScanResult(res.result);
						}
					},
					fail: (err) => {
						uni.showToast({
							title: '扫描失败',
							icon: 'none'
						});
					}
				});
			},
			handleScanResult(result) {
				if (this.except_arr.includes(result)) {
					uni.showToast({
						title: '扫码重复',
						icon: 'none'
					})
				} else {
					const reg = /^[0-9]{6,18}\.[0-9]{1,3}$/;
					if (reg.test(result)) {
						scanCode({
							bar_code: 'J' + result
						}).then((data) => {
							uni.showToast({
								title: '添加成功',
								icon: 'success'
							});
							// 播放扫码成功
							this.audio.play();
							// 添加振动 - 震动1秒（1000毫秒）
							// #ifdef APP-PLUS
							if (plus.device.vibrate) {
								plus.device.vibrate(1000); // 振动 1 秒
							}
							// #endif
							this.except_arr.push(result);
							this.input.unshift({ // 新数据添加到开头
								code: data.data.bar_code,
								time: formatDate(new Date())
							});
							this.total++
						}).catch(e => {
							console.log('e', e)
							uni.showToast({
								title: '添加失败',
								icon: 'none'
							});
						});
					} else {
						uni.showToast({
							title: '条码格式不正确',
							icon: 'none'
						});
					}
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		padding: 30rpx;
		background-color: #f5f7fa;
		height: 100vh
	}

	/* 新增搜索框样式 */
	.search-box {
		display: flex;
		align-items: center;
		padding: 20rpx;
		background: #fff;
		border-radius: 16rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
		margin-bottom: 20rpx;
	}

	.search-input {
		flex: 1;
		padding: 0 20rpx;
		font-size: 28rpx;
		height: 60rpx;
	}

	.placeholder-style {
		color: #ccc;
		font-size: 28rpx;
	}

	.refresh-btn {
		background-color: #409eff;
		color: white;
		margin-bottom: 20rpx;
	}

	.scan-btn {
		background-color: #67c23a;
		color: white;
		margin-bottom: 30rpx;
	}

	.scan-result {
		font-size: 28rpx;
		color: #909399;
		margin: 20rpx 0;
		text-align: center;
	}

	/* 表格样式 */
	.table-container {
		background-color: #fff;
		border-radius: 16rpx;
		overflow: hidden;
		box-shadow: 0 2rpx 12rpx 0 rgba(0, 0, 0, 0.1);
		margin-top: 20rpx;
	}

	.table-header {
		display: flex;
		background-color: #409eff;
	}

	.table-body {
		max-height: 100vh;
		overflow-y: auto;
		::v-deep .uni-scroll-view-content {
		    min-height: 101%; /* 强制超出容器高度 */
		  }
	}
	
	/* 安卓设备专属优化 */
	/* #ifdef APP-PLUS && ANDROID */
	.table-body {
	  overflow-anchor: none; /* 禁用锚定滚动 */
	}
	/* #endif */

	.table-row {
		display: flex;
		border-bottom: 1rpx solid #ebeef5;
		transition: all 0.3s;

		&:last-child {
			border-bottom: none;
		}

		&:nth-child(odd) {
			background-color: #fafafa;
		}

		&:hover {
			background-color: #f5f7fa;
		}
	}

	.table-cell {
		flex: 1;
		padding: 24rpx;
		font-size: 28rpx;
		text-align: center;
		word-break: break-all;
		display: flex;
		align-items: center;
		/* 确保单元格内容垂直居中 */
		justify-content: center;
		/* 水平居中 */

		&.code-cell {
			color: #303133;
			font-weight: 500;
		}

		&.time-cell {
			color: #606266;
		}

		&.time-header {
			display: flex;
			align-items: center;
			justify-content: center;
			cursor: pointer;

			.sort-icon {
				margin-left: 10rpx;
				display: flex;
				align-items: center;
			}
		}
	}

	.header-cell {
		color: #fff;
		font-weight: bold;
		font-size: 30rpx;
	}

	.empty-tip {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 60rpx 0;

		image {
			width: 200rpx;
			height: 200rpx;
			margin-bottom: 20rpx;
			opacity: 0.6;
		}

		text {
			color: #909399;
			font-size: 28rpx;
		}
	}

	/* 响应式调整 */
	@media (max-width: 500px) {
		.table-cell {
			padding: 20rpx 10rpx;
			font-size: 26rpx;
		}
	}
</style>